package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketAdExample;
import com.cskaoyan.market.db.mapper.MarketAdMapper;
import com.cskaoyan.market.util.MybatisUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class AdminAdServiceImpl implements AdminAdService{

    @Override
    public List<MarketAd> list(String page, String limit, String sort, String order,String name,String content) {
        SqlSession session = MybatisUtils.getSession();
        MarketAdMapper mapperAdMapper = session.getMapper(MarketAdMapper.class);
        MarketAdExample marketAdExample = new MarketAdExample();
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        if(!StringUtils.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if(!StringUtils.isEmpty(content)){
            criteria.andContentLike("%"+content+"%");
        }
        marketAdExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketAd> marketAds = mapperAdMapper.selectByExample(marketAdExample);
        session.close();
        return marketAds;
    }

    @Override
    public Integer createAd(MarketAd marketAd) {
        SqlSession session = MybatisUtils.getSession();
        MarketAdMapper mapperAdMapper = session.getMapper(MarketAdMapper.class);
        MarketAdExample marketAdExample = new MarketAdExample();
        Integer i=mapperAdMapper.insert(marketAd);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public Integer updateAd(MarketAd marketAd) {
        SqlSession session = MybatisUtils.getSession();
        MarketAdMapper mapperAdMapper = session.getMapper(MarketAdMapper.class);
        MarketAdExample marketAdExample = new MarketAdExample();
        Integer i=mapperAdMapper.updateByPrimaryKey(marketAd);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public Integer deleteAd(MarketAd marketAd) {
        SqlSession session = MybatisUtils.getSession();
        MarketAdMapper mapperAdMapper = session.getMapper(MarketAdMapper.class);
        Integer i=mapperAdMapper.deleteByPrimaryKey(marketAd.getId());
        session.commit();
        session.close();
        return i;
    }
}
